package com.rlax.web.base;

import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsApi;
import com.jfinal.weixin.sdk.api.UserApi;
import com.rlax.framework.common.Consts;
import com.rlax.web.model.User;
import com.rlax.web.model.WeixinUser;

/**
 * 
 * @author Rlax
 *
 */
public abstract class BaseWeiXinController extends BaseController {

	/**
	 * 微信是否绑定用户
	 * @return
	 */
	public boolean hasBind() {
		return getWeiXinUser() != null;
	}
	
	/**
	 * 获取微信登录用户
	 * @return
	 */
	public String getUserNo() {
		String loginName = getWeiXinUser().getNo();
		if (StrKit.isBlank(loginName)) {
			return null;
		}
		
		User user = User.dao.findByName(loginName);
		if (user == null) {
			return null;
		}
		
		return user.getNo();
	}

	/**
	 * 获取微信登录用户
	 * @return
	 */
	public WeixinUser getWeiXinUser() {
		String openId = getOpenId();
		return WeixinUser.dao.findByOpenId(openId);
	}
	
	/**
	 * 获取微信登录用户
	 * @return
	 */
	public WeixinUser getWeiXinUser(String openId) {
		return WeixinUser.dao.findByOpenId(openId);
	}
	
	/**
	 * 获取openid
	 * @return
	 */
	public String getOpenId() {
		return getSnsAccessToken().getOpenid();
	}
	
	/**
	 * 获取accessToken
	 * @return
	 */
	public SnsAccessToken getSnsAccessToken() {
		SnsAccessToken token = (SnsAccessToken) getSession().getAttribute(Consts.WEIXIN_SESSION_CODE);
		
		/**
		token.getExpiresIn()
		if (token == null)
			return null;
		if (StrKit.notBlank(token.getErrorCode().toString()))
			return null;
		if (expiredTime < System.currentTimeMillis())
			return false;
		return access_token != null;
		*/
		
		return token;
	}
	
	/**
	 * 获取微信用户资料
	 * @param accessToken
	 * @param openId
	 * @return
	 */
	public ApiResult getSnsUserInfo(String accessToken, String openId) {
		ApiConfigKit.setThreadLocalApiConfig(getApiConfig());
		return SnsApi.getUserInfo(accessToken, openId);
	}

	/**
	 * 获取微信用户资料
	 * @param accessToken
	 * @param openId
	 * @return
	 */
	public ApiResult getCgiUserInfo(String openId) {
		ApiConfigKit.setThreadLocalApiConfig(getApiConfig());
		return UserApi.getUserInfo(openId);
	}
	
	public ApiConfig getApiConfig() {
		ApiConfig ac = new ApiConfig();
		
		// 配置微信 API 相关常量
		ac.setToken(PropKit.get("weixin.token"));
		ac.setAppId(PropKit.get("weixin.appid"));
		ac.setAppSecret(PropKit.get("weixin.appSecret"));
		/**
		 *  是否对消息进行加密，对应于微信平台的消息加解密方式：
		 *  1：true进行加密且必须配置 encodingAesKey
		 *  2：false采用明文模式，同时也支持混合模式
		 */
		ac.setEncryptMessage(PropKit.getBoolean("weixin.encryptMessage", false));
		ac.setEncodingAesKey(PropKit.get("weixin.encodingAesKey", "setting it in config file"));
		return ac;
	}
}
